<?php
class MsepCore_View_Helper_GetCategoriesRecursively extends Zend_View_Helper_Abstract {
	
	protected $_position;
	
	public function __construct() {
		$this->_position = 0;
	}
	
	public function getCategoriesRecursively($item, $init = false) {
		$table = Engine_Api::_ ()->getDbTable ( 'categories', 'news' );
		
		$select = $table->select ()->where ( 'parent_id = ?', $item->category_id );
		
		$child_categories = $table->fetchAll ( $select );
		
		if (count ( $child_categories ) == 0)
			return "";
		
		$return = "";
		
		$view = Zend_Registry::get ( 'Zend_View' );
		
		$index = 0;
		
		foreach ( $child_categories as $child_category ) {
			$return .= "<tr>
                                  <td>" . $view->htmlImage ( 'application/modules/MsepCore/externals/images/indent.png', 'indent', array ('style' => 'margin-left: ' . intval ( ($this->getPosition ( $child_category, true )) * 16 ) . 'px; vertical-align: top;' ) ) . $child_category->category_name . "</td>
                                  <td>" . $child_category->user_id . "</td>
                                  <td>" . $child_category->getUsedCount () . "</td>
                                  <td>
                                        " . $view->htmlLink ( array ('route' => 'admin_default', 'module' => 'news', 'controller' => 'settings', 'action' => 'edit-category', 'id' => $child_category->category_id ), $view->translate ( 'edit' ), array ('class' => 'smoothbox' ) ) . "
                                        |
                                        " . $view->htmlLink ( array ('route' => 'admin_default', 'module' => 'news', 'controller' => 'settings', 'action' => 'delete-category', 'id' => $child_category->category_id ), $view->translate ( 'delete' ), array ('class' => 'smoothbox' ) ) . "
                                  </td>
                             </tr>";
			
			$return .= $this->getCategoriesRecursively ( $child_category );
		}
		
		return $return;
	}
	
	public function getPosition($item, $init = false) {
		if ($init)
			$this->_position = 0;
		
		$table = Engine_Api::_ ()->getDbtable ( 'categories', 'news' );
		$select = $table->select ()->where ( 'category_id = ?', $item->parent_id );
		$categories = $table->fetchAll ( $select );
		
		if (count ( $categories ) > 0) {
			$this->_position ++;
			
			return $this->getPosition ( $categories [0] );
		} else {
			return $this->_position - 1;
		}
	}

}